package volatileTest;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @program: javase
 * @description: volatile 不能保证原子性
 * @author: lld
 * @create: 2021-04-22 22:10
 **/
public class Test2 {

//    private static volatile int i=0;

//    使用原子类
    private static volatile AtomicInteger i=new AtomicInteger(0);

    private static  void add(){
        i.getAndIncrement();
    }

    public static void main(String[] args) {
        for (int i1 = 0; i1 < 10; i1++) {
            new Thread(()->{
                for (int i2 = 0; i2 < 1000; i2++) {
                    add();
                }
            }).start();
        }
        System.out.println(Thread.activeCount());
//main线程礼让上面线程执行完，一定要用while,不能用if
        while (Thread.activeCount()>2){//gc,main
            Thread.yield();
        }
        System.out.println(Thread.activeCount());
        System.out.println(i);//理论i=1000
    }
}
